﻿using Newtonsoft.Json;
using RestSharp;
using SCM.Common.Extensions;
using System;
using System.Collections.Generic;
using System.Text;

namespace SCM.Common.SMS
{
    public class ShareSDKHelper : IShareSdk
    {
        private string appKey;
        private string secretKey;
        public ShareSDKHelper(string appkey, string secret)
        {
            appKey = appkey;
            secretKey = secret;
        }
        /// <summary>
        /// 秒验证
        /// </summary>
        /// <param name="model"></param>
        /// <param name="appkey"></param>
        /// <param name="secret"></param>
        /// <returns></returns>
        public string SdkClientFreeLogin(string token, string opToken, string operatorStr, string md5 = "")
        {
            RestClient client = new RestClient();
            client.Timeout = 10000;
            client.BaseUrl = new Uri("http://identify.verify.mob.com");
            var request = new RestRequest(Method.POST);
            request.RequestFormat = DataFormat.Json;
            request.JsonSerializer = new MTSerializer();
            request.Resource = "/auth/auth/sdkClientFreeLogin";
            Dictionary<string, object> data = new Dictionary<string, object>();
            data.Add("appkey", appKey);
            if (!string.IsNullOrWhiteSpace(md5))
            {
                data.Add("md5", md5);
            }
            data.Add("opToken", opToken);
            data.Add("operator", operatorStr);
            data.Add("timestamp", UnitityHelper.GetTimeStamp());
            data.Add("token", token);

            data.Add("sign", GetSign(data, secretKey).ToLower());
            request.AddJsonBody(data);
            IRestResponse response = client.Execute(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                data = JsonConvert.DeserializeObject<Dictionary<string, object>>(response.Content);
                if (data["status"].ToString() == "200")
                {
                    string str = data["res"].ToString();
                    str = EncryptHelper.DecryptDES(str, secretKey, Encoding.Default.GetBytes("00000000"));
                    try
                    {
                        data = JsonConvert.DeserializeObject<Dictionary<string, object>>(str);
                        if (data["isValid"].ToString() == "1")
                        {
                            return data["phone"].ToString();
                        }
                    }
                    catch
                    {
                        return "";
                    }
                    return "";
                }
                else
                {
                    throw new BusinessException("验证请求错误：" + data["error"].ToString(), JsonConvert.SerializeObject(data), ResultCode.LoginFailed);
                }
            }
            else
            {
                string error = "";
                try
                {
                    data = JsonConvert.DeserializeObject<Dictionary<string, object>>(response.Content);
                    error = data["error"].ToString();
                }
                catch
                {
                }
                throw new BusinessException("验证请求错误：" + error, JsonConvert.SerializeObject(data), ResultCode.LoginFailed);
            }
        }
        Dictionary<string, object> responseData;
        public string SMSLogin(string phone, string code, string zone)
        {
            RestClient client = new RestClient();
            client.Timeout = 10000;
            client.BaseUrl = new Uri("https://webapi.sms.mob.com/");
            var request = new RestRequest(Method.POST);
            request.RequestFormat = DataFormat.None;
            request.JsonSerializer = new MTSerializer();

            request.Resource = "/sms/verify";

            string data = $"appkey={appKey}&amp;phone={phone}&amp;zone={zone}&amp;code={code}";

            request.AddParameter("text/plain", data, ParameterType.RequestBody);

            IRestResponse response = client.Execute(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                responseData = JsonConvert.DeserializeObject<Dictionary<string, object>>(response.Content);
                if (responseData.ContainsKey("status"))
                {
                    switch (responseData["status"].ToString())
                    {
                        case "200": return "";
                        case "405": return "AppKey为空";
                        case "406": return "AppKey无效";
                        case "456": return "国家代码或手机号码为空";
                        case "457": return "手机号码格式错误";
                        case "466": return "请求校验的验证码为空";
                        case "467": return "请求校验验证码频繁（5分钟内同一个appkey的同一个号码最多只能校验三次）";
                        case "468": return "验证码错误";
                        case "474": return "没有打开服务端验证开关";
                    }
                }
                throw new BusinessException("短信验证错误(返回数据错误)", data, ResultCode.Error);
            }
            else
            {
                throw new BusinessException($"短信验证错误(请求错误):{response.ErrorMessage}", data, ResultCode.Error);
            }
        }
        private string GetSign(Dictionary<string, object> data, string secret)
        {
            if (data == null)
            {
                return null;
            }
            StringBuilder plainText = new StringBuilder();
            foreach (var item in data)
            {
                if (!"sign".Equals(item.Key) && item.Value != null)
                {
                    plainText.Append($"&{item.Key}={item.Value}");
                }
            }
            string substring = plainText.Remove(0, 1).ToString();
            return EncryptHelper.HashMD5String(substring + secret, Encoding.UTF8);
        }


        public string PushMessage(SharePushModel model)
        {
            if (model == null)
                return "消息体不能为空";
            model.Appkey = appKey;
            model.Source = "webapi";
            RestClient client = new RestClient();
            client.Timeout = 10000;
            client.BaseUrl = new Uri("http://api.push.mob.com/v3/push/");
            var request = new RestRequest(Method.POST);
            request.RequestFormat = DataFormat.None;
            request.JsonSerializer = new MTSerializer();

            request.Resource = "createPush";

            request.AddHeader("key", appKey);
            request.AddHeader("sign", EncryptHelper.HashMD5String($"{JsonConvert.SerializeObject(model)}{secretKey}", Encoding.UTF8));
            request.AddJsonBody(model);
            IRestResponse response = client.Execute(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
               
                responseData = JsonConvert.DeserializeObject<Dictionary<string, object>>(response.Content);
                if (responseData.ContainsKey("status"))
                {
                    if (responseData["status"].ToString() == "200")
                    {
                        return "";
                    }
                    else
                    {
                        return responseData["error"].ToString();
                    }
                }
                return responseData["error"].ToString();
            }
            else
            {
                string error = response.Content;
               
                if (string.IsNullOrWhiteSpace(error))
                {
                    error = response.ErrorMessage;
                }
                return error;
            }
        }
    }
}
